<!DOCTYPE>
<html xmlns:th="http://www.thymeleaf.org">
<html>

<head>
    <meta charset="UTF-8">
    <title>未来小说网--作品信息</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/cropperjs/1.5.7/cropper.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css">
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <link rel="stylesheet" href="../../resources/font/iconfont.css" th:href="@{/resources/font/iconfont.css}">
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../../resources/css/WorkInformation.css" th:href="@{/resources/css/WorkInformation.css}">
</head>
<script th:inline="javascript" async>
    window.onload = function() {
        function popup_over(icon,color,contant){
            $('body').append('<div class="popup_over" style="text-align: center; line-height: 80px; left: 50%; top: 50%; transform: translate(-50%,-50%); background-color: white; position: fixed; width: 180px; height: 80px; border: 1px solid #D5D6D5; z-index: 1000;"><i class="iconfont '+icon+'" style="font-size: 30px;color: '+color+';"></i><span style="font-size: 16px; position: relative; bottom: 5px;"> '+contant+'</span></div>');
            setTimeout(function(){
                $('.popup_over').remove();
                // clear('.popup_over');
            },1500)
        };
        function getNowFormatDate() {
            var date = new Date();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            var minute = date.getMinutes();
            var second = date.getSeconds();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            if (minute >= 0 && minute <= 9) {
                minute = "0" + minute;
            }
            if (second >= 0 && second <= 9) {
                second = "0" + second;
            }
            var currentdate = date.getFullYear() + "年" + month + "月" + strDate +
                "日 " + date.getHours() + ":" + minute + ":" + second;
            return currentdate;
        }
        var tags = [];
        var actor = ["haha", "heihei"];
        $("#book-tags").keydown(function(event) {
            if (event.keyCode == 32) {
                if ($("#book-tags").val().length >= 5) {
                    alert("标签不得超过三个字")
                    $("#book-tags").val("");
                } else {
                    var str = $("#book-tags").val();
                    var test = " <div class=\"tags-s\">\n" +
                        "<a href=\"###\" class=\"tags-text\">" + str + "</a>\n" +
                        "<i class=\"fa fa-close close2\" ></i>\n" +
                        "</div>";
                    $(".tags").append(test);
                    $("#book-tags").val("");
                }
            }
        });
        $("#book-act").keydown(function(event) {
            if (event.keyCode == 32) {
                var str = $("#book-act").val();
                var test = " <div class=\"tags-s\">\n" +
                    "<a href=\"###\" class=\"tags-text2\">" + str + "</a>\n" +
                    "<i class=\"fa fa-close close2\" ></i>\n" +
                    "</div>";
                $(".acts").append(test);
                $("#book-act").val("");
            }
        });
        $(".tags").on('click', '.close2', function() {
            $(this).parent().remove();
        });
        $(".acts").on('click', '.close2', function() {
            $(this).parent().remove();
        });

        function GetTags() {
            const contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
            $.ajax({
                url: contextPath+"/api/novel/tags/all",
                type: "get",
                data: "",
                success: function(data) {
                    console.log(data);
                    for (var i = 0; i < data.length; i++) {
                        $("#tag").append(" <option value='" + "" + data[i] + "" + "'>")
                    }
                },
                error: function(data) {
                    console.log(data)
                }
            });
        }
        GetTags();

        $("#create-work").click(function() {
            if ($("#book-name").val().length > 15) {
                popup_over('icon-sad','#d81e06',"书名不能超过15个字");
            } else if ($("#book-type").val() == "") {
                popup_over('icon-sad','#d81e06',"书名不能为空");
            } else if ($("#book-type").val() == "") {
                popup_over('icon-sad','#d81e06',"书品系列不能为空");
            } else if ($("#copyright").val() == "-请选择-") {
                popup_over('icon-sad','#d81e06',"请选择版权");
            } else if ($("#book-press").val() == "") {
                popup_over('icon-sad','#d81e06',"请输入出版社");
            }
            else {
                const str = $("#image-to-crop").attr("src").endsWith("/img/addimg.png")?null:$("#image-to-crop").attr("src");
                var  $inputArr  =  $('.tags-text');
                var  result  =   [];
                $inputArr.each(function() {
                    //将每个input的值放进结果集
                    result.push($(this).text());
                });
                var  $inputArr2  =  $('.tags-text2');
                var  result2  =   [];
                $inputArr2.each(function() {
                    //将每个input的值放进结果集
                    result2.push($(this).text());
                });
                console.log(result);
                const contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
                $.ajax({
                    url: contextPath+"/api/novel/addIndex",
                    type: "post",
                    dataType: "JSON",
                    contentType: "application/json",
                    data: JSON.stringify({
                        "copyright": $("#copyright").val()=='公版'?"NO_COPYRIGHT":$("#copyright").val()=='转载'?"REPRINT":$("#copyright").val()=='同人'?"FAN_FICTION":"ORIGINAL",
                        "title": $("#book-name").val(),
                        "authors": result2,
                        "description": $("#book-intro").val(),
                        "tags": result,
                        "series": $("#book-type").val(),
                        "publisher": $("#book-press").val(),
                        "pubdate": getNowFormatDate(),
                        "coverImgUrl":str
                    }),
                    success: function(data) {
                        $("#TEXT").html("创建成功");
                        console.log(data.uniqueId);
                        window.location.href = "/future-novel/novel/" + data.uniqueId + "/write";
                    },
                    error() {

                    }
                })
            }
        });
    }
</script>
<body>
    <div class="box3">
        <div class="work-info" style="float: right;margin: 100px 140px 100px 0;">
            <div class="top-title">
                <div class="top-title-box">
                    <span style="line-height: 50px;font-size:17px;color: white;float: right;">创建作品</span>
                </div>

            </div>
            <div class="work-info-form">
                    <div class="form-box">
                        <div class="form-list">
                            <dl>
                                <dd class="">
                                    <span>标题</span>
                                    <input name="book-name" id="book-name" class="form-inputs" type="text" required>
                                    <p>15字内，请勿添加书名号等特殊符号</p>
                                </dd>
                                <dd>
                                    <span>系列</span>
                                    <input id="book-type" class="form-inputs" style="width: 200px;" type="text" required>
                                    <p>例如：魔幻，武侠，都市....</p>
                                </dd>
                                <dd>
                                    <span>版权</span>
                                    <select id="copyright">
                                <option selected>-请选择-</option>
                                <option>公版</option>
                                <option>转载</option>
                                <option>同人</option>
                                <option>原创</option>
                            </select>
                                </dd>
                                <dd>
                                    <span>作品分类标签(输入空格隔开标签)</span>
                                    <input style="height: 30px;padding: 0;resize: none;" id="book-tags" list="tag" class="form-inputs">
                                    <datalist id="tag">

                            </datalist>
                                    <div class="tags">

                                    </div>

                                </dd>
                                <dd>
                                    <span>作者(输入空格隔开作者)</span>
                                    <input style="height: 30px;padding: 0;resize: none;" id="book-act" class="form-inputs">
                                    <div class="acts">

                                    </div>

                                </dd>
                                <dd>
                                    <span>出版社</span>
                                    <input name="book-press" id="book-press" class="form-inputs" type="text" required>
                                </dd>
                                <dd>
                                    <span>简介</span>
                                    <textarea class="form-inputs" id="book-intro" style="resize: none;font-size:20px;height: 70px"></textarea>
                                </dd>
                            </dl>
                        </div>
                        <div class="create">
                            <button type="button" id="create-work" data-toggle="modal" data-target="#myModal">创建作品</button>
                        </div>
                    </div>
            </div>
        </div>
        <noscript>You need to enable JavaScript to run this app.</noscript>
        <div id="upload-part" class="upload-img">
            <p>双击切换选择与移动，支持拖动</p>
            <img id="image-to-crop" onclick="document.getElementById('img-input').click()" class="preview-img"  th:src="@{/resources/img/addimg.png}"/>
            <label for="img-input">选择图片</label><br />
            <input type="file" accept="image/*" id="img-input"></input>
            <br />
            <input type="range" min="0" value="0" max="360" id="rotate-input" style="width: 190px;"></input>
            <br />
            <button id="confirm-btn" class="blue-btn">确认并上传</button>
        </div>
    </div>
        <div class='progress-mask'>
        </div>
        <div class="progress">
            <!-- 可以替换成进度条之类的 -->
            <h1>请稍后...</h1>
        </div>

        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://cdn.bootcdn.net/ajax/libs/cropperjs/1.5.7/cropper.min.js"></script>
        <script  th:inline="javascript" async>
            function popup_over(icon,color,contant){
                $('body').append('<div class="popup_over" style="text-align: center; line-height: 80px; left: 50%; top: 50%; transform: translate(-50%,-50%); background-color: white; position: fixed; width: 180px; height: 80px; border: 1px solid #D5D6D5; z-index: 1000;"><i class="iconfont '+icon+'" style="font-size: 30px;color: '+color+';"></i><span style="font-size: 16px; position: relative; bottom: 5px;"> '+contant+'</span></div>');
                setTimeout(function(){
                    $('.popup_over').remove();
                    // clear('.popup_over');
                },1500)
            };
            function show_progress(value) {
                document.getElementsByClassName("progress-mask")[0].style.visibility = value ? 'visible' : 'hidden';
                document.getElementsByClassName("progress")[0].style.visibility = value ? 'visible' : 'hidden';
            }
            const image = document.getElementById('image-to-crop');
            $('#img-input').change(function() {
                var path = this.value;
                if (path == undefined || path == null || path == '') {
                    popup_over('icon-sad','#d81e06',"请先选择图片");
                    return;
                }
                const cropper = image.cropper;
                if (cropper != undefined) {
                    cropper.destroy();
                }
                var reader = new FileReader();
                reader.onload = function(e) {
                    image.setAttribute('src', e.target.result);
                    const cropper = new Cropper(image, {
                        aspectRatio: 3/4,
                        viewMode: 1,
                        rotatable: true
                    });
                }
                reader.readAsDataURL(this.files[0]);
            });
            $('#rotate-input').change(function() {
                const cropper = image.cropper;
                if (cropper != undefined) {
                    cropper.rotateTo(this.value);
                }
            });
            $('#confirm-btn').click(function() {
                const cropper = image.cropper;
                const contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
                if (cropper != undefined) {
                    show_progress(true);
                    cropper.getCroppedCanvas().toBlob(function(blob) {
                        const formData = new FormData();
                        formData.append('file', blob);
                        $.ajax({
                            url:contextPath+"/api/img/upload",
                            method: 'PUT',
                            data: formData,
                            processData: false,
                            contentType: false,
                            success(data) {
                                console.log(data);
                                cropper.destroy();
                                image.setAttribute('src', data.url);
                                show_progress(false);
                            },
                            error(jqXHR) {
                                const data = JSON.parse(jqXHR.responseText);
                                console.log(data);
                                alert(data.errorMessage);
                                show_progress(false);

                            }
                        });
                    });
                } else {
                    popup_over('icon-sad','#d81e06',"未选择文件");
                }
            });
            const uploadDropBox = document.getElementById("upload-part");
            function doNothing(e) {
                e.stopPropagation();
                e.preventDefault();
            }
            uploadDropBox.addEventListener('dragenter', doNothing, false);
            uploadDropBox.addEventListener('dragover', doNothing, false);
            uploadDropBox.addEventListener('drop', function(e) {
                doNothing(e);
                const dt = e.dataTransfer;
                if (dt.files == undefined || dt.files.length == 0) return;
                const imgFile = dt.files[0];
                if (imgFile != undefined && imgFile.type.startsWith('image/')) {
                    const cropper = image.cropper;
                    if (cropper != undefined) {
                        cropper.destroy();
                    }
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        image.setAttribute('src', e.target.result);
                        const cropper = new Cropper(image, {
                            aspectRatio: 1,
                            viewMode: 1,
                            rotatable: true
                        });
                    }
                    reader.readAsDataURL(imgFile);
                }
            }, false);
        </script>

</body>

</html>